// pinia
// import { defineStore } from "pinia";

// vuex
import { createStore, Commit } from "vuex";
import axios from "@/services/axios";
import router from "@/router/index";
// data为一个泛型，默认是一个对象
export interface ResponseType<P = object> {
  code: number;
  msg: string;
  data: P;
}
export interface UserProps {
  isLogin: boolean;
  nickName?: string;
  _id?: string;
  column?: string;
  email?: string;
  avatar?: ImageProps;
  description?: string;
  url?:string
}

export interface ImageProps {
  _id?: string;
  url?: string;
  createdAt?: string;
  fitUrl?: string;
}

export interface ColumnProps {
  _id: string;
  title: string; //专栏标题
  avatar?: ImageProps; //专栏图片
  description: string; // 专栏描述
}
export interface PostProps {
  _id?: string;
  title: string; //文章标题
  content: string; //文章内容
  image?: ImageProps | string; //文章图片(在创建文章时也可能是传图片id)
  createdAt?: string; //创建时间
  column: string; // 文章对应的专栏id
  excerpt?: string; //文章摘要
  author: string; //用户id
}

export interface GlobalDataProps {
  error: GlobalErrorProps;
  token: string;
  loading: boolean;
  columns: ColumnProps[];
  posts: PostProps[];
  user: UserProps;
}

export interface GlobalErrorProps {
  status: boolean;
  message?: string;
}

//get mutations 公共方法
const getAddCommit = async (
  url: string,
  mutationsName: string,
  commit: Commit
) => {
  const { data } = await axios.get(url);
  mutationsName && commit(mutationsName, data);
  return data;
};

//post mutations 公共方法
const postAddCommit = async (
  url: string,
  mutationsName: string,
  commit: Commit,
  payload: any
) => {
  const { data } = await axios.post(url, payload);
  commit(mutationsName, data);
  return data;
};

export default createStore<GlobalDataProps>({
  state: {
    error: {
      status: false,
    },
    token: localStorage.getItem("token") || "",
    loading: false,
    columns: [],
    posts: [],
    // 缓存的user数据，防止刷新vuex数据丢失
    user: JSON.parse(localStorage.getItem("user") as string) || {
      isLogin: Boolean(localStorage.getItem("isLogin")) || false,
      nickName: "",
      column: "", //专栏id
      _id: '', //用户id
    },
  },
  getters: {
    // 获取专栏
    getColumnById: (state) => (id: string) => {
      return state.columns.find((c) => c._id === id);
    },
    //获取专栏对应的文章列表
    getPostsByCid: (state) => (cid: string) => {
      return state.posts.filter((post) => post.column === cid);
    },
  },
  mutations: {
    // 登录------测试使用
    // login(state) {
    //   state.user = { ...this.user, isLogin: true, name: "login", column: 1 };
    // },
    // 创建文章
    createPost(state, newPost) {
      state.posts.push(newPost);
    },
    // 获取专栏列表
    fetchColumns(state, data) {
      state.columns = data.list;
    },
    // 获取某个专栏详情
    fetchColumn(state, data) {
      state.columns = [data];
    },
    // 获取某个专栏下的文章列表
    fetchPosts(state, rawData) {
      state.posts = rawData.list;
    },
    // 获取文章详情
    // fetchPost(state, rawData) {
    //   state.posts.data[rawData.data._id] = rawData.data
    // },
    // 设置loading
    setLoading(state, status) {
      state.loading = status;
    },
    // 设置error
    setError(state, e: GlobalErrorProps) {
      state.error = e;
    },
    // 获取当前用户信息
    fetchCurrentUser(state, rawData) {
      state.user = { isLogin: true, ...rawData };
      localStorage.setItem("isLogin", String(state.user.isLogin));
    },
    // 登录
    login(state, rawData) {
      state.token = rawData.token;
      localStorage.setItem("token", state.token);
    },
    // 登出
    logOut(state) {
      state.user.isLogin = false;
      state.token = "";
      localStorage.clear();
      router.push("/login");
    },
  },
  actions: {
    // 登录
    login({ commit, dispatch }, payload) {
      return postAddCommit("/api/user/login", "login", commit, payload).then(
        async () => await dispatch("fetchCurrentUser")
      );
    },
    // 获取专栏列表
    fetchColumns(context) {
      return getAddCommit("/api/columns", "fetchColumns", context.commit);
    },
    // 获取某个专栏详情
    fetchColumn({ commit }, cid) {
      return getAddCommit("/api/columns/" + cid, "fetchColumn", commit);
    },
    // 获取某个专栏下的文章列表
    fetchPosts({ commit }, cid) {
      return getAddCommit(`/api/columns/${cid}/posts`, "fetchPosts", commit);
    },
    // 获取当前用户信息
    fetchCurrentUser({ commit }) {
      return getAddCommit(`/api/user/current`, "fetchCurrentUser", commit);
    },
    // 创建文章
    createPost({ commit }, payload) {
      return postAddCommit("/api/posts", "createPost", commit, payload)
    },
    //获取文章
    fetchPost({ commit }, cid) {
      return getAddCommit(`/api/posts/${cid}`, '', commit);
    },
  },
  modules: {},
});
